package com.tanhua.server.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.tanhua.common.utils.UserThreadLocal;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.pojo.RecommendUser;
import com.tanhua.dubbo.pojo.UserInfo;
import com.tanhua.dubbo.vo.PageInfo;
import com.tanhua.server.config.RecommendUserConfig;
import com.tanhua.server.config.TodayBestConfig;
import com.tanhua.server.vo.PageResult;
import com.tanhua.server.vo.RecommendUserQueryParam;
import com.tanhua.server.vo.TodayBest;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class TodayBestService {

    @Autowired
    private UserService userService;

    //问题：写死到配置文件，不方便修改与维护？ -- 由学生自己解决这个问题
    //@Value("${tanhua.sso.defaultUser}")
    //private Long defaultUser;

    @Autowired
    private TodayBestConfig todayBestConfig;

    @Autowired
    private RecommendUserConfig recommendUserConfig;
    @DubboReference(version = "1.0.0")
    private RecommendUserApi recommendUserApi;

    @DubboReference(version = "1.0.0")
    private UserInfoApi userInfoApi;

    /**
     * 查询今日佳人
     *
     *
     * @return
     */
    public TodayBest queryTodayBest() {
        //获取User对象，无需对User对象校验，其一定不为null
        Long userId = UserThreadLocal.get();

        //通过调用dubbo服务查询得分最高的用户
        RecommendUser recommendUser = this.recommendUserApi.queryWithMaxScore(userId);
        if (ObjectUtil.isEmpty(recommendUser)) {
            //如果为空,给出一个默认的推荐用户
            recommendUser = new RecommendUser();
            recommendUser.setUserId(todayBestConfig.getDefaultUser());
            recommendUser.setToUserId(userId);
            //随机一个得分
            recommendUser.setScore(99D);
        }
        //根据用户id查询用户的基本信息
        UserInfo userInfo = this.userInfoApi.queryByUserId(recommendUser.getUserId());
        //类型转换
        TodayBest todayBest = BeanUtil.toBeanIgnoreError(userInfo, TodayBest.class);
        //设置性别
        todayBest.setGender(userInfo.getSex().name().toLowerCase());
        //设置id
        todayBest.setId(userInfo.getUserId());
        //设置缘分值
        todayBest.setFateValue(recommendUser.getScore().longValue());
        return todayBest;

    }

    /**
     * 查询推荐用户列表
     *
     *
     * @param queryParam
     * @return
     */
    public PageResult queryRecommendation( RecommendUserQueryParam queryParam) {
        //获取User对象，无需对User对象校验，其一定不为null
        Long userId = UserThreadLocal.get();

        PageResult pageResult = new PageResult();
        pageResult.setPage(queryParam.getPage());
        pageResult.setPagesize(queryParam.getPagesize());
        //查询dubbo服务，查询推荐列表
        PageInfo<RecommendUser> pageInfo = this.recommendUserApi.queryPageInfo(userId, queryParam.getPage(), queryParam.getPagesize());
        List<RecommendUser> records = pageInfo.getRecords();

        if (CollUtil.isEmpty(records)) {
            //默认的推荐列表
            // 不建议返回null
            List<Object> defaultUserList = this.recommendUserConfig.getDefaultUserList();
            //查询用户信息
            List<UserInfo> userInfoList = this.userInfoApi.queryByUserIdList(defaultUserList);
            if (CollUtil.isEmpty(userInfoList)) {
                return pageResult;
            }
            //目标：封装TodayBest列表
            ArrayList<TodayBest> todayBestArrayList = new ArrayList<>();
            for (UserInfo userInfo : userInfoList) {
                //数据转换
                TodayBest todayBest = BeanUtil.toBeanIgnoreError(userInfo, TodayBest.class);
                todayBest.setGender(userInfo.getSex().name().toLowerCase());
                todayBest.setId(userInfo.getUserId());
                // 查找到该用户所对应的RecommendUser对象，目的是获取它的得分
                todayBest.setFateValue(Convert.toLong(RandomUtil.randomDouble(80, 98)));
                //排除今日佳人的用户
                if (!ObjectUtil.equal(this.queryTodayBest().getId(), todayBest.getId())) {
                    todayBestArrayList.add(todayBest);
                }
            }
            //对集合排序
            Collections.sort(todayBestArrayList, (o1, o2) -> Convert.toInt(o2.getFateValue() - o1.getFateValue()));

            pageResult.setItems(todayBestArrayList);
            return pageResult;
        }

        //获取所有用户id
        List<Object> userIdList = CollUtil.getFieldValues(records, "userId");
        //查询用户信息
        List<UserInfo> userInfoList = this.userInfoApi.queryByUserIdList(userIdList);
        if (CollUtil.isEmpty(userInfoList)) {
            return pageResult;
        }
        //目标：封装TodayBest列表
        ArrayList<TodayBest> todayBestArrayList = new ArrayList<>();
        for (UserInfo userInfo : userInfoList) {
            //数据转换
            TodayBest todayBest = BeanUtil.toBeanIgnoreError(userInfo, TodayBest.class);
            todayBest.setGender(userInfo.getSex().name().toLowerCase());
            todayBest.setId(userInfo.getUserId());
            // 查找到该用户所对应的RecommendUser对象，目的是获取它的得分
            for (RecommendUser record : records) {
                if (ObjectUtil.equal(record.getUserId(), userInfo.getUserId())) {
                    todayBest.setFateValue(record.getScore().longValue());
                    break;
                }
            }
            //排除今日佳人的用户
            if (!ObjectUtil.equal(this.queryTodayBest().getId(), todayBest.getId())) {
                todayBestArrayList.add(todayBest);
            }

        }

        //对集合排序
        Collections.sort(todayBestArrayList, (o1, o2) -> Convert.toInt(o2.getFateValue() - o1.getFateValue()));

        pageResult.setItems(todayBestArrayList);
        return pageResult;
    }
}
